//var mongoose = require('mongoose')
//mongoose.connect('mongodb://localhost:27017/Ants')
var entries = require('./jsonRes')
var User = require('./../models/user')




exports.addUser = function (data, cb) {
  User.findOne({
    username: data.username,
    password:data.password
  }, function (err, doc) {
    if (err) {
      console.log(err)
    } else if (doc !== null) {
      entries.code = 99 
      console.log("用户已存在")  //用户是否存在
      cb(false, entries)//callback回调
    } else if (doc === null) {
      var user = new User({
        username: data.username,//req.body.username
        password: data.password//前端传值进来
      })
      user.save(function (err, doc) { //保存用户
        if (err) {
          entries.code = 99
          cb(false, err)
        } else {
          console.log(doc)
          cb(true, entries)
        }
      })
    }
  })
}

exports.findUser = function (data, cb) {
  User.findOne({
    username: data.body.username,//req.body.username
    password:data.body.password
  }, function (err, doc) {
    var user = (doc !== null) ? doc.toObject() : ''//doc 不为空的话就取doc.toobject
    console.log(user)
    if (err) {
      console.log(err)
    } else if (doc === null) {
      entries.code = 99 
      cb(false, entries)  //回调函数返回false和entries的值  //查无此用户
    } else if (user.password !== data.body.password) {
      entries.code = 99
      console.log("密码错误")
      cb(false, entries)
    } else {
      entries.data = user
      entries.code = 0
      console.log("success find use")
      data.session.username=user.username//req.session.username
      data.session.password=user.password
     
      console.log(data.session.username)
      cb(true, entries) 
    }
  })
}